import { GetQiniuUploadToken } from '@/services/api';
import { LoadingOutlined } from '@ant-design/icons';
import { Input, Upload, UploadProps } from 'antd';
import { useState } from 'react';

interface UploadFileProps {
  value?: any;
  onChange?: any;
  title?: string;
}

const handleUpload = async (options: any) => {
  const { file, onSuccess } = options;

  const res = await GetQiniuUploadToken();
  const token = res.data.token;
  const fmData = new FormData();
  fmData.append('file', file);
  fmData.append('token', token); // multiple

  const response = await fetch(res.data.host, {
    method: 'POST',
    body: fmData,
  });
  const data = await response.json();
  console.log(data);
  onSuccess(data);
};

const UploadFile = (props: UploadFileProps) => {
  const { value, onChange } = props;
  const [loading, setLoading] = useState(false);
  // const [fileUrl, setFileUrl] = useState('');
  const uploadProps: UploadProps = {
    name: 'file',
    showUploadList: false,
    customRequest: handleUpload,
    maxCount: 1,
    onChange(info) {
      if (info.file.status === 'uploading') {
        setLoading(true);
        return;
      }
      if (info.file.status === 'done') {
        // console.log("iiiii",info)
        // Get this url from response in real world.
        // console.log(info.file.response.data);
        // console.log(info);
        setLoading(false);
        // setFileUrl(info.file.response.url);
        onChange(info.file.response.url);
      }
    },
  };
  return (
    <>
      <Upload
        {...uploadProps}
        disabled={loading}
        className="componentUploadFile"
        style={{
          width: '100%',
        }}
      >
        {/* {fileUrl ? (
            <div>
              <div>{fileUrl.substring(fileUrl.lastIndexOf('/') + 1)}</div>
              <div>点击重新上传</div>
            </div>
          ) : (
            <Button loading={loading}>选择上传文件</Button>
          )} */}
        {loading ? (
          <LoadingOutlined />
        ) : (
          <Input
            value={value === '' ? undefined : value}
            placeholder="点击上传"
          />
        )}
      </Upload>
    </>
  );
};

export default UploadFile;
